package mt.tratapedidos;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import mt.comm.ServerSideMessage.Type;
import mt.dummy.ClientSideMessageDummy;
import mt.dummy.ServerCommDummy;
import mt.dummy.ServerSideMessageDummy;
import mt.dummy.User;

public class TrataPedidos extends Thread {

	
		private ObjectInputStream socketIn;
		private ObjectOutputStream socketOut;
		private ServerCommDummy serverCommDummy;
		private ServerSideMessageDummy msg;
		private boolean stop;
		

		public TrataPedidos(ServerCommDummy serverCommDummy,ObjectInputStream socketIn, ObjectOutputStream socketOut) {
			this.socketIn=socketIn;
			this.socketOut=socketOut;
			this.serverCommDummy=serverCommDummy;
		}
		
		public void run(){
			stop=true;
			
			while(stop){
				try {
					 msg= (ServerSideMessageDummy) socketIn.readObject();
					
					 
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
				if(msg.getType().equals(Type.NEW_ORDER)){
					serverCommDummy.addMessagesToQueue(msg);
				}
				
				if( msg.getType().equals(Type.CONNECTED)){
					User novo = new User(socketIn, socketOut, msg.getSenderNickname());
					serverCommDummy.addMessagesToQueue(msg);
					serverCommDummy.addUser(novo);
				}
				if ( msg.getType().equals(Type.DISCONNECTED)){
					ClientSideMessageDummy msg = new ClientSideMessageDummy(mt.comm.ClientSideMessage.Type.ERROR, null);
					try {
						socketOut.writeObject(msg);
						stop=false;
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
				
					
					
				
			}
			
		}
		
		

	}



